package work02.w5.control.server;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
/**
 * 通过消息方式提醒的闹钟服务。
 * @author Eric
 * @date 2012-10-7
 */
public class MyAlarmServer {
	private static MyAlarmServer me;
	private Timer timer;
	private MyCalendarServeCenter center;
	private MyEventFactory eventProduce;
	private Map<Integer,TimerTask> alarm = new HashMap<Integer, TimerTask>();
	
	private MyAlarmServer() {
		timer = new Timer();
		center=MyCalendarServeCenter.getInstance();
		eventProduce = MyEventFactory.getNewInstance();
	}

	public static MyAlarmServer getInstance() {
		if (me == null)
			me = new MyAlarmServer();
		return me;
	}
/**
 *
 * @param time
 * @param event
 * @return 返回唯一标示码
 */
	public int addAlarm(Date time, final MyEvent event) {
		int id=event.hashCode()+time.hashCode();
		TimerTask task = new TimerTask() {

			@Override
			public void run() {
				center.sendMyEvent(event);
			}
		};
		timer.schedule(task,time);
		alarm.put(id, task);
		return id;
		
	}
/**
 * 
 * @param time
 * @param event
 * @param period
 * @return 返回唯一标识码 
 */
	public int addAlarm(Date time, final MyEvent event, long period) {
		int id=(int) (time.hashCode()+event.hashCode()+period);
		TimerTask task = new TimerTask() {

			public void run() {
				center.sendMyEvent(event);
			}
		};
		timer.schedule(task, time, period);
		alarm.put(id, task);
		return id;
	}
	/**
	 * 通过id移除已经设置好的闹钟服务
	 * @param id
	 */
	public void removeAlarm(int id){
		TimerTask task = alarm.remove(id);
		task.cancel();
	}
}
